package com.suke.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.*;

/*
 * <>:T E K V
 * T:Type
 * E:Elements
 * K:key
 * V:value
 * */
public class RedisUtil {

    //Jedis:等同于Connection
    public static Jedis getJedis() {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(500);
        config.setMaxIdle(5);
        config.setMaxWaitMillis(100);
        JedisPool jedisPool =
                new JedisPool(config, "192.168.60.130", 6379, 1000, "123456");
        Jedis jedis = jedisPool.getResource();
        return jedis;
    }

    //把Map<String,Object>转换成Map<String,String>
    public static Map<String, String> mapToMap(Map<String, Object> map) {
        Map<String, String> data = new HashMap<String, String>();
        for (Map.Entry<String, Object> m : map.entrySet()) {
            data.put(m.getKey(), m.getValue() + "");
        }
        return data;
    }

    //把数据库查询出来的数据存储到Redis中
    public static <T> void dbToRedis(List<T> data, Jedis jedis, int index, String keyPattern) {
        //选库
        jedis.select(index);
        Map<String, Object> map = new HashMap<String, Object>();
        for (T t : data) {
            //把对象的数据放入到Map中
            BeanUtil.beanToMap(t, map, false, true);
            //Map<String,Object>转换成Map<String,String>
            Map<String, String> tempData = mapToMap(map);
            jedis.hmset(keyPattern + jedis.incr("index"), tempData);
        }
    }

    public static <T> void dbToRedis(T t, Jedis jedis, int index, String key) {
        //选库
        jedis.select(index);
        Map<String, Object> map = new HashMap<String, Object>();
        //把对象的数据放入到Map中
        BeanUtil.beanToMap(t, map, false, true);
        //Map<String,Object>转换成Map<String,String>
        Map<String, String> tempData = mapToMap(map);
        jedis.hmset(key, tempData);
    }

    //把Redis数据查询出来封装到对象中
    public static <T> List<T> redisToJava(Class<T> clazz, Jedis jedis, int index, String keyPattern) {
        //选库
        jedis.select(index);

        //获取满足条件的key
        Set<String> keys = jedis.keys(keyPattern);

        List<T> data = new ArrayList<T>();
        for (String key : keys) {
            Map<String, String> map = jedis.hgetAll(key);
            T t = BeanUtil.mapToBean(map, clazz,
                    false, new CopyOptions().ignoreNullValue());
            data.add(t);
        }
        return data;
    }
}